<?php
namespace App\Http\Controllers\Business\App\Wallet;

use App\Http\Controllers\Controller;
use App\Models\AllInPay;
use App\Models\DoubleCoupon;
use App\Models\Log;
use App\Models\Recharge;
use App\Models\User;
use Illuminate\Support\Facades\Redis;
use League\Flysystem\Exception;

class RechargeNotifyController extends Controller
{
    //支付宝充值
    public function alipayNotify() {
        $alipayNotify = new \AlipayNotify();
        if($alipayNotify->getResponse($_POST['notify_id'])) {
            if($alipayNotify->getSignVeryfy($_POST, $_POST['sign'])) {
                $log = new Log();
                $log->logs = json_encode($_POST);
                $log->save();
                $ordernumber=$_POST["out_trade_no"];
                $money=@$_POST["total_amount"];
                $payshopnumber=@$_POST['trade_no'];
                if(!$money) {
                    $money=@$_POST["total_fee"];
                }
                $attach = $_POST["body"];

                if($_POST['trade_status'] == 'TRADE_FINISHED') {

                } else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                    $userdata = Redis::get('Recharge:OrderNumber:'.$ordernumber);
                    if($userdata) {
                        Redis::del('Recharge:OrderNumber:'.$ordernumber); 
                        $userdata = json_decode($userdata,true);
                        if($userdata['apiversion'] != 'v2') {
                            //老版本
                            if ($money == $userdata['money'] && $userdata['userid'] == $attach) {
                                if (!Recharge::where('userid', $userdata['userid'])->first()) {
                                    $firstrechargetime = User::find($userdata['userid']);
                                    $firstrechargetime->firstrechargetime = date('Y-m-d H:i:s', time());
                                    $firstrechargetime->save();
                                }
                                $recharge = new Recharge;
                                $recharge->userid = $userdata['userid'];
                                $recharge->money = $money;
                                $recharge->status = '1';
                                $recharge->path = '支付宝';
                                $recharge->rechargenumber = $ordernumber;
                                $recharge->payshopnumber = $payshopnumber;
                                $recharge->doublemoney = $money * 2;
                                $recharge->doublestatus = '1';
                                $recharge->doubletime = date('Y-m-d H:i:s', time());
                                User::find($userdata['userid'])->increment('balance', $money * 2);
                                User::find($userdata['userid'])->increment('point', $money);
                                $recharge->sharestatus = '0';
                                $recharge->save();
                            }
                        } else {
                            //新版本v2, 2017-02-16
                            if (bccomp($money,$userdata['actualmoney'],2) == 0 && $userdata['userid'] == $attach) {
                                $controller = new RechargeNotifyController();
                                $controller->addRechargeByV2Version($userdata['userid'], $userdata['money'], $userdata['fee'], $userdata['actualmoney'], '支付宝', $ordernumber, $payshopnumber);
                            }
                        }
                    }

                }
                echo "success";
            } else {
                //验证签名失败
                echo "sign fail";
            }
        } else {
            //验证是否来自支付宝的通知失败
            echo "response fail";
        }
    }
    //微信充值
    public function wechatNotify() {
        $notify = new \Notify_pub();
        $xml = file_get_contents("php://input");
        if(!$xml)
        {
            exit;
        }
        $notify->saveData($xml);
        try {
            $log = new Log();
            libxml_disable_entity_loader(true);
            $values = json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA));
            $log->logs = $values;
            $log->save();
        }
        catch (Exception $e)
        {

        }
        if($notify->checkSign() == FALSE){
            $notify->setReturnParameter("return_code","FAIL");
            $notify->setReturnParameter("return_msg","签名失败");
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");
            $notify->setReturnParameter("return_msg","OK");
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;
        if($notify->checkSign() == TRUE) {
            $ordernumber=$notify->data["out_trade_no"];
            $money=$notify->data["total_fee"]*0.01;
            $payshopnumber=$notify->data['transaction_id'];
            $attach = $notify->data["attach"];
            $userdata = Redis::get('Recharge:OrderNumber:'.$ordernumber);
            if($userdata) {
                Redis::del('Recharge:OrderNumber:' . $ordernumber);
                $userdata = json_decode($userdata, true);
                if ($userdata['apiversion'] != 'v2') {
                    //老版本
                    if ($money == $userdata['money'] && $userdata['userid'] == $attach) {
                        if (!Recharge::where('userid', $userdata['userid'])->first()) {
                            $firstrechargetime = User::find($userdata['userid']);
                            $firstrechargetime->firstrechargetime = date('Y-m-d H:i:s', time());
                            $firstrechargetime->save();
                        }
                        $recharge = new Recharge;
                        $recharge->userid = $userdata['userid'];
                        $recharge->money = $money;
                        $recharge->status = '1';
                        if ($notify->data["appid"] == 'wx5b9f6cb38192bd41') {
                            $recharge->path = '微信公众平台支付';
                        } elseif ($notify->data["appid"] == 'wx5a540a7265ed4c94') {
                            $recharge->path = '微信APP支付';
                        }
                        $recharge->rechargenumber = $ordernumber;
                        $recharge->payshopnumber = $payshopnumber;
                        $recharge->doublemoney = $money * 2;
                        $recharge->doublestatus = '1';
                        $recharge->doubletime = date('Y-m-d H:i:s', time());
                        User::find($userdata['userid'])->increment('balance', $money * 2);
                        User::find($userdata['userid'])->increment('point', $money);
                        $recharge->sharestatus = '0';
                        $recharge->save();
                    }
                } else {
                    //新版本
                    if (bccomp($money,$userdata['actualmoney'],2) == 0 && $userdata['userid'] == $attach) {
                        if ($notify->data["appid"] == 'wx5b9f6cb38192bd41') {
                            $path = '微信公众平台支付';
                        } elseif ($notify->data["appid"] == 'wx5a540a7265ed4c94') {
                            $path = '微信APP支付';
                        }
                        $controller = new RechargeNotifyController();
                        $controller->addRechargeByV2Version($userdata['userid'], $userdata['money'], $userdata['fee'], $userdata['actualmoney'], $path, $ordernumber, $payshopnumber);

                    }
                }
            }
        }
    }
    //通联支付
    public function allinpayNotify() {
        $params = array();
        foreach ($_POST as $key => $val) {
            $params[$key] = $val;
        }
        $log = new Log();
        $log->logs = json_encode($_POST);
        $log->save();
        if (count($params) < 1) {
            echo "error";
            exit();
        }
        if (AllInPay::ValidSign($params) && $params['trxstatus'] == '0000') {
            $ordernumber = $params['cusorderid'];
            $money = $params['trxamt'] * 0.01;
            $payshopnumber = $params['trxid'];
            $attach = $params['trxreserved'];
            $userdata = Redis::get('Recharge:OrderNumber:' . $ordernumber);
            if ($userdata) {
                Redis::del('Recharge:OrderNumber:' . $ordernumber);
                $userdata = json_decode($userdata, true);
                if ($money == $userdata['money'] && $userdata['userid'] == $attach) {
                    if (!Recharge::where('userid', $userdata['userid'])->first()) {
                        $firstrechargetime = User::find($userdata['userid']);
                        $firstrechargetime->firstrechargetime = date('Y-m-d H:i:s', time());
                        $firstrechargetime->save();
                    }
                    $recharge = new Recharge;
                    $recharge->userid = $userdata['userid'];
                    $recharge->money = $money;
                    $recharge->status = '1';
                    $recharge->path = '通联微信支付';
                    $recharge->rechargenumber = $ordernumber;
                    $recharge->payshopnumber = $payshopnumber;
                    $recharge->doublemoney = $money * 2;
                    $recharge->doublestatus = '1';
                    $recharge->doubletime = date('Y-m-d H:i:s', time());
                    User::find($userdata['userid'])->increment('balance', $money * 2);
                    User::find($userdata['userid'])->increment('point', $money);
                    $recharge->sharestatus = '0';
                    $recharge->save();
                }
                if ($userdata['apiversion'] != 'v2') {
                    //老版本
                    if ($money == $userdata['money'] && $userdata['userid'] == $attach) {
                        if (!Recharge::where('userid', $userdata['userid'])->first()) {
                            $firstrechargetime = User::find($userdata['userid']);
                            $firstrechargetime->firstrechargetime = date('Y-m-d H:i:s', time());
                            $firstrechargetime->save();
                        }
                        $recharge = new Recharge;
                        $recharge->userid = $userdata['userid'];
                        $recharge->money = $money;
                        $recharge->status = '1';
                        $recharge->path = '通联微信支付';
                        $recharge->rechargenumber = $ordernumber;
                        $recharge->payshopnumber = $payshopnumber;
                        $recharge->doublemoney = $money * 2;
                        $recharge->doublestatus = '1';
                        $recharge->doubletime = date('Y-m-d H:i:s', time());
                        User::find($userdata['userid'])->increment('balance', $money * 2);
                        User::find($userdata['userid'])->increment('point', $money);
                        $recharge->sharestatus = '0';
                        $recharge->save();
                    }
                } else {
                    //新版本
                    if (bccomp($money,$userdata['actualmoney'],2) == 0 && $userdata['userid'] == $attach) {
                        $path = '通联微信支付';
                        $controller = new RechargeNotifyController();
                        $controller->addRechargeByV2Version($userdata['userid'], $userdata['money'], $userdata['fee'], $userdata['actualmoney'], $path, $ordernumber, $payshopnumber);

                    }
                }
            }
            echo "success";
        } else {
            echo "erro";
        }
    }

    //版本v2 新增充值记录
    public function addRechargeByV2Version($userId, $money, $fee, $actualMoney, $path, $orderNumber, $payShopNumber) {
        if(!$userId||!$money||!$actualMoney||!$path||!$orderNumber||!$payShopNumber||($money+$fee!=$actualMoney)) {
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
        if (!Recharge::where('userid', $userId)->first()) {
            User::where('id', $userId)->update(['firstrechargetime'=>date('Y-m-d H:i:s')]);
        }
        $recharge = new Recharge;
        $recharge->userid = $userId;
        $recharge->money = $money;
        $recharge->fee = $fee;
        $recharge->actualmoney = $actualMoney;
        $recharge->status = '1';
        $recharge->path = $path;
        $recharge->rechargenumber = $orderNumber;
        $recharge->payshopnumber = $payShopNumber;
        $recharge->doublemoney = $money * 2;
        $recharge->doublestatus = '1';
        $recharge->doubletime = date('Y-m-d H:i:s');
        User::find($userId)->increment('balance', $money * 2);
        User::find($userId)->increment('point', $money);
        $recharge->sharestatus = '0';
        $recharge->save();
        return ['status'=>'success', 'message'=>'新增成功'];
    }


    //老的支付宝充值
    public function oldAlipayNotify() {
        $alipayNotify = new \AlipayNotify();
        if($alipayNotify->getResponse($_POST['notify_id'])) {
            if($alipayNotify->getSignVeryfy($_POST, $_POST['sign'])) {
                $log = new Log();
                $log->logs = json_encode($_POST);
                $log->save();
                $ordernumber=$_POST["out_trade_no"];
                $money=@$_POST["total_amount"];
                $payshopnumber=@$_POST['trade_no'];
                if(!$money) {
                    $money=@$_POST["total_fee"];
                }
                $attach = $_POST["body"];
                if($_POST['trade_status'] == 'TRADE_FINISHED') {

                } else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
                    $userdata = Redis::get('Recharge:OrderNumber:'.$ordernumber);
                    if($userdata) {
                        Redis::del('Recharge:OrderNumber:'.$ordernumber);
                        $userdata = json_decode($userdata,true);
                        if($money == $userdata['money'] && $userdata['userid'] == $attach) {
                            if(! Recharge::where('userid',$userdata['userid'])->first()) {
                                $firstrechargetime = User::find($userdata['userid']);
                                $firstrechargetime->firstrechargetime = date('Y-m-d H:i:s', time());
                                $firstrechargetime->save();
                            }
                            $recharge = new Recharge;
                            $recharge->userid = $userdata['userid'];
                            $recharge->money = $money;
                            $recharge->status = '1';
                            $recharge->path = '支付宝';
                            $recharge->rechargenumber = $ordernumber;
                            $recharge->payshopnumber = $payshopnumber;
                            $recharge->doublemoney = $money * 2;
                            $recharge->doublestatus = '1';
                            $recharge->doubletime = date('Y-m-d H:i:s', time());
                            User::find($userdata['userid'])->increment('balance',$money*2);
                            User::find($userdata['userid'])->increment('point',$money);
                            $recharge->sharestatus = '0';
                            $recharge->save();
                        }
                    }
                }
                echo "success";
            } else {
                //验证签名失败
                echo "sign fail";
            }
        } else {
            //验证是否来自支付宝的通知失败
            echo "response fail";
        }
    }
    //老的微信充值
    public function oldWechatNotify() {
        $notify = new \Notify_pub();
        $xml = file_get_contents("php://input");
        $notify->saveData($xml);
        if($notify->checkSign() == FALSE){
            $notify->setReturnParameter("return_code","FAIL");
            $notify->setReturnParameter("return_msg","签名失败");
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");
            $notify->setReturnParameter("return_msg","OK");
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;
        if($notify->checkSign() == TRUE) {
            $ordernumber=$notify->data["out_trade_no"];
            $money=$notify->data["total_fee"]*0.01;
            $payshopnumber=$notify->data['transaction_id'];
            $attach = $notify->data["attach"];
            $userdata = Redis::get('Recharge:OrderNumber:'.$ordernumber);
            if($userdata) {
                Redis::del('Recharge:OrderNumber:'.$ordernumber);
                $userdata = json_decode($userdata,true);
                if($money == $userdata['money'] && $userdata['userid'] == $attach) {
                    if(! Recharge::where('userid',$userdata['userid'])->first()) {
                        $firstrechargetime = User::find($userdata['userid']);
                        $firstrechargetime->firstrechargetime = date('Y-m-d H:i:s', time());
                        $firstrechargetime->save();
                    }
                    $recharge = new Recharge;
                    $recharge->userid = $userdata['userid'];
                    $recharge->money = $money;
                    $recharge->status = '1';
                    if($notify->data["appid"] == 'wx5b9f6cb38192bd41') {
                        $recharge->path = '微信公众平台支付';
                    } elseif($notify->data["appid"] == 'wx5a540a7265ed4c94') {
                        $recharge->path = '微信APP支付';
                    }
                    $recharge->rechargenumber = $ordernumber;
                    $recharge->payshopnumber = $payshopnumber;
                    $recharge->doublemoney = $money * 2;
                    $recharge->doublestatus = '1';
                    $recharge->doubletime = date('Y-m-d H:i:s', time());
                    User::find($userdata['userid'])->increment('balance',$money*2);
                    User::find($userdata['userid'])->increment('point',$money);
                    $recharge->sharestatus = '0';
                    $recharge->save();
                }
            }
        }
    }

    //通联支付
    public function oldAllinpayNotify() {
        $params = array();
        foreach ($_POST as $key => $val) {
            $params[$key] = $val;
        }
        $log = new Log();
        $log->logs = json_encode($_POST);
        $log->save();
        if (count($params) < 1) {
            echo "error";
            exit();
        }
        if (AllInPay::ValidSign($params) && $params['trxstatus'] == '0000') {
            $ordernumber = $params['cusorderid'];
            $money = $params['trxamt'] * 0.01;
            $payshopnumber = $params['trxid'];
            $attach = $params['trxreserved'];
            $userdata = Redis::get('Recharge:OrderNumber:' . $ordernumber);
            if ($userdata) {
                Redis::del('Recharge:OrderNumber:' . $ordernumber);
                $userdata = json_decode($userdata, true);
                if ($money == $userdata['money'] && $userdata['userid'] == $attach) {
                    if (!Recharge::where('userid', $userdata['userid'])->first()) {
                        $firstrechargetime = User::find($userdata['userid']);
                        $firstrechargetime->firstrechargetime = date('Y-m-d H:i:s', time());
                        $firstrechargetime->save();
                    }
                    $recharge = new Recharge;
                    $recharge->userid = $userdata['userid'];
                    $recharge->money = $money;
                    $recharge->status = '1';
                    $recharge->path = '通联微信支付';
                    $recharge->rechargenumber = $ordernumber;
                    $recharge->payshopnumber = $payshopnumber;
                    $recharge->doublemoney = $money * 2;
                    $recharge->doublestatus = '1';
                    $recharge->doubletime = date('Y-m-d H:i:s', time());
                    User::find($userdata['userid'])->increment('balance', $money * 2);
                    User::find($userdata['userid'])->increment('point', $money);
                    $recharge->sharestatus = '0';
                    $recharge->save();
                }
            }
            echo "success";
        } else {
            echo "erro";
        }
    }

}